<template>
  <div class="app-container">


    <!-- 5-还箱单 10-箱属 15-还箱令 -->
    <!-- <cz-tages :bottomLine="true" :typeList="typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages> -->
    <span style="float: right;">
      <!-- <el-button type="primary" @click="" size="small" plain round>导出</el-button> -->
      <el-button type="primary" v-if="orderTypeval == '10'" @click="goCreateReturn(5)" size="small" plain round>开还箱单</el-button>
      <!-- <template v-else>
        <el-button type="primary" @click="goCreateReturn(15)" size="small" plain round>开还箱令</el-button>
        <el-button type="primary" @click="goCreateReturn(10)" size="small" plain round>开箱属</el-button>
      </template> -->
    </span>
    

    <Table ref="tableRef" v-bind="table" style="width: 100%;" @pageChange="onTablePageChange" @showInfo="showInfo"
      @downloadFile="downloadFile" @showReturnRecord="showReturnRecord" @activeAddPacking="activeAddPacking">
    </Table>

    <!-- 集装箱选择 -->
    <el-drawer v-model="param.drawerSelectBox" :with-header="false">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>集装箱选择
      </span>
      <el-input v-model.trim="param.containerNos" @input="getBoxTableData" type="text"
        placeholder="请输入箱号 HNKU0000000,HNKU0000000" style="float: right;margin-top: 40px;" />
      <div style="height:40px"></div>
      <el-table :data="param.selectBoxTable" @selection-change="handleSelectionBoxChange" style="margin-top: 80px;">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="containerNo" label="箱号"> </el-table-column>
        <el-table-column prop="boxType" label="箱型"> </el-table-column>
        <el-table-column prop="agentName" label="回调服务商"> </el-table-column>
        <el-table-column prop="agentUserName" label="带箱人"> </el-table-column>
        <el-table-column prop="boxEastUserName" label="回箱人"> </el-table-column>
      </el-table>
      <div style="margin-top: 40px;height: 50px;">
        <el-button @click="handleChoiceBox" type="primary" style="float: right;width: 100px;"> 确定 </el-button>
      </div>
    </el-drawer>

    <!-- 开还箱单 -->
    <el-drawer v-model="param.drawer1" :before-close="close" :show-close="false" size="40%">
      <div style="font-weight: 700;font-size: 18px;margin-top: -20px;">
        <el-row>
          <el-col :span="6">
            <span v-if="param.oprType == 5">开还箱单</span>
            <span v-if="param.oprType == 10">开箱属</span>
            <span v-if="param.oprType == 15">开还箱令</span>
          </el-col>
        </el-row>
      </div>
      <div style="margin-top: 40px;">
      </div>
      <el-table :data="param.rentOrderTable" style="width: 100%;">
        <el-table-column prop="orderNo" label="订单号"> </el-table-column>
        <el-table-column prop="createTime" label="下单日期"> </el-table-column>
        <template v-if="param.oprType == 5">
          <el-table-column prop="returnedQuantity" label="已还箱量"> </el-table-column>
          <el-table-column prop="returnWaitQuantity" label="未还箱量"> </el-table-column>
        </template>
        <template v-else>
          <el-table-column prop="packedQuantity" label="已开箱量"> </el-table-column>
          <el-table-column prop="packedWaitQuantity" label="未开箱量"> </el-table-column>
        </template>
        <el-table-column prop="agentName" label="回调服务商"> </el-table-column>
        <el-table-column prop="agentUserName" label="联系人"> </el-table-column>
        <el-table-column prop="createTime" label="联系电话" width="140">
          <template #default="scope">
            <span v-if="scope.row.agentUserAreaCode">+{{ scope.row.agentUserAreaCode }} </span>
            {{ scope.row.agentUserTel }}
          </template>
        </el-table-column>
      </el-table>
      <div>
        <div style="margin-top: 40px;">箱型量 {{ getFormatNum(param.rentOrderTable) }}</div>
      </div>
      <el-form :model="param" ref="returnFormRef" :rules="returnRules" style="margin-top: 40px;">
        <template v-if="param.oprType == 5">
          <el-form-item prop="instruction">
            <div>
              <redStar />还箱指令号
            </div>
            <el-input v-model="param.instruction" style="width: 100%;" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item prop="returnValidityPeriod">
            <div>
              <redStar />还箱单有效期范围
            </div>
            <el-date-picker v-model="param.returnValidityPeriod" type="daterange" range-separator="~"
              start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
          </el-form-item>
        </template>
        <template v-if="param.oprType == 15">
          <el-form-item>
            <div> 还箱指令号 </div>
            <el-input v-model="param.instruction" style="width: 100%;" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item>
            <div> 还箱单有效期范围 </div>
            <el-date-picker v-model="param.returnValidityPeriod" type="daterange" range-separator="~"
              start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
          </el-form-item>
        </template>
        <el-form-item prop="yardName_">
          <div>
            <redStar />堆场名称
          </div>
          <yardSelect v-model="param.yardName_" :yardName="param.yardName_"  :selectName="'yardName'" :needInfo="true" @yardId="yardInfoData"
            style="width:100%" :placeholder="'请输入堆场名称'">
          </yardSelect>
        </el-form-item>
        <el-form-item>
          <div>
            <redStar />堆场地址
          </div>
          <el-input v-model="yardInfo.yardAddress" disabled style="width: 100%;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item prop="contacts">
          <div>
            <redStar />联系人
          </div>
          <!-- <el-input v-model="yardInfo.contacts" disabled style="width: 100%;" placeholder="请输入"></el-input> -->
          <el-select v-model="yardInfo.contacts" @change="handleYardContactsChange">
            <el-option v-for="item in yardInfo.yardContacts" :key="item.yardContactSerialNo" :label="item.contacts"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>
            <redStar />联系电话
          </div>
          <el-input v-model="yardInfo.tel" disabled style="width: 100%;" placeholder="请输入">
            <template #prepend v-if="yardInfo?.areaCode">+{{yardInfo.areaCode}}</template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <div>
            <redStar />堆场作业时间
          </div>
          <el-input v-model="yardInfo.workTime" disabled style="width:100%" placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="param.oprType == 10" prop="boxOwnerContent">
          <div>
            <redStar />箱属内容
          </div>
          <el-input v-model="param.boxOwnerContent" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <div style="padding: 40px 0;">
        <redStar />
        <redStar /><el-button @click="choiceBox" :disabled="!yardInfo.id" icon="edit">选择箱号</el-button>
      </div>
      <el-table :data="selectBoxList">
        <el-table-column prop="containerNo" label="箱号" />
      </el-table>
      <div style="margin-top: 40px;">
        <redStar v-if="param.oprType > 5" /> {{ returnTypeFilter(param.oprType) }}附件
      </div>
      <img-upload ref="packingRef" :fileList="fileList" :limit="10" :type="'pdf_jpg_png_zip'" :multiple="true"/>
      <!-- <div style="margin-top: 40px;">备注 </div>
      <el-input v-model="param.remark" type="textarea" placeholder="请输入内容" /> -->
      <div style="margin-top: 40px;height: 50px;">
        <el-button @click="handleSubmit" type="primary" style="float: right;width: 100px;"> 提交
        </el-button>
      </div>
    </el-drawer>

    <!-- 还箱记录 -->
    <el-drawer v-model="param.drawer3" :with-header="false">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>还箱记录
      </span>
      <div style="float: right;margin-top: 60px;">
        <span>应还箱量：{{ rowData.totalReturnQuantity }} 个</span> &nbsp;
        <span>实还箱量：{{ rowData.returnedQuantity }} 个</span>
      </div>
      <el-table :data="packingRecord" style="margin-top: 100px;">
        <el-table-column prop="containerNo" label="箱号" />
        <el-table-column prop="boxType" label="箱型" />
        <el-table-column prop="returnDate" label="还箱日期" />
        <el-table-column prop="agentName" label="租客" />
      </el-table>
    </el-drawer>
    <!-- 还箱单详情 -->
    <indexInfo ref="indexInfoRef" :isAgent="false"></indexInfo>

  </div>
</template>

<script setup lang="ts">
import { downloadIamge } from '@/utils/download'
import Table from '@/components/table'
import redStar from '@/views/components/redStar.vue';
import { formatDate } from '@/utils'
import czTages from '@/components/chengzhiTags'
import imgUpload from '@/components/upload/index.vue'
import { boxEastSelectReturnOrderList as getRentOrderList } from '@/api/orderManage/index'
import { boxEastSelectReturnOrderList as getHuiDiaoOrderList } from '@/api/boxCallBack/order'
import yardInfoCard from '@/views/components/boxYard/yardInfo.vue'
import indexInfo from '@/views/components/huanXiangManage/indexInfo.vue'

import { getBoxEastTable, getReturnData, addReturn, cancelReturn, downloadReturn ,getBoxruntEastTable} from '@/api/orderManage/returnBox'
import { getDetailTable, getReturnData as getReturnEastData, updateReturnMark, updateReturnDate, updateDetailFile, finishReturnBoxDetail } from '@/api/orderManage/returnBoxDetail'
import yardSelect from '@/components/citySelect/yardSelect.vue';
import { getTable as getBoxTable } from '@/api/boxManage/index'
import { computed, getCurrentInstance, onMounted, onActivated, reactive, ref, watch,nextTick,inject } from 'vue';
import { useRoute } from 'vue-router'

import {
  Plus,
  Delete,
  Edit,
  Message,
  Search,
  Download,
  Upload,
  Refresh,
  UploadFilled,
  ChatLineSquare
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
const isAgent=inject('isAgent') //当前等角色  true 货代角色  false 集装箱公司角色
const formData = inject('formData')

const param = reactive({
  pageNum: 1,
  pageSize: 10,
  returnBoxType: '',
  //table
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提', },
    { value: '5', label: '全新', },
  ],
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  returnTypeOptions: [ //5-还箱单 10-箱属  15-还箱令
    // { value: '5', label: '还箱单', },
    { value: '10', label: '箱属', },
    { value: '15', label: '还箱令', },
  ],
  //开还箱单列表
  rentOrderTable: [{ orderNo: '', planPickupDate: '', createTime: '' }],
  rentBoxTable: [{ boxType: '', boxQuantity: '', boxCondition: '' }],
  selectTable: [{ orderNo: '', planPickupDate: '', createTime: '', boxType: '', boxQuantity: '', boxCondition: '' }],
  selectBoxTable: [{ containerNo: '', boxType: '', inDays: '', boxCondition: '' }],
  isExist:false
});
const content=ref('从货代公司收到还箱单之日起，以天为单位计算有效期，不足一天按一天计算。')
const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'returnBoxNo', colWidth: '130', title: '单据号', type: '<a>', command: 'showInfo', isCheck: true },
    // { key: 'orderList', key2: 'orderNo', colWidth: '120', title: '订单号', type: '/', isCheck: true },
    { key: 'returnBoxType', colWidth: '80', title: '单据类型', type: 'filter', filter: { 5: '还箱单', 10: '箱属', 15: '还箱令' }, isCheck: true },
    { key: 'yardName',colWidth: '100', title: '堆场名称', type: 'text', isCheck: true },
    { key: 'residueReturnDays', colWidth: '140', title: '剩余还箱天数', isTooltip: true, tooltip: "该还箱单剩余有效还箱天数", type: 'days', after: '天', isCheck: true },
    { key: 'totalReturnQuantity', colWidth: '80', title: '总箱量', type: 'totalQuantity', isCheck: true },
    { key: 'returnedQuantity', colWidth: '80', title: '已提箱量', type: 'totalQuantity', isCheck: true },
    { key: 'totalQuantity',key2: 'packedQuantity', colWidth: '80', title: '未提箱量', type: 'quantity', isCheck: true },
    { key: 'returnValidityPeriodStart', colWidth: '150', key2: 'returnValidityPeriodEnd', title: '还箱单据有效期范围', type: 'range', isCheck: true },
    { key: 'agentName', title: '客户',colWidth: '150', type: 'text', isCheck: true },
    // { key: 'agentUserName', title: '联系人',colWidth: '80', type: 'text', isCheck: true },
    // { key: 'agentUserTel',colWidth: '140', title: '联系电话', type: 'phoneNumber',areaCode:"agentUserAreaCode", isCheck: true },
    // { key: 'boxEastOperatorUserName', title: '联系人',colWidth: '150', type: 'text', isCheck: true },
    { key: 'returnBoxStatus', colWidth: '80', title: '状态', type: 'statusHuanxiang', isCheck: true },
    {
      key: 'operate',
      colWidth: '150',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          // icon: 'Download',
          command: 'downloadFile',
          // content: '下载还箱单',
          name:'下载',
          isShow: (row: any) => {
            // return row.status <= 10;
            return JSON.parse(row.pdfFile)!='';
          },
        },
        {
          // icon: 'ChatLineSquare',
          command: 'showReturnRecord', //param.drawer3
          // content: '还箱记录',
          name:'查看',
        },

      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: false, // 是否分页
    total: 0, // 分页总数
    loading: false
  },
});

//校验规则
const validatePlanPackingDate = (rule: any, value: any, callback: any) => {
  if (value[0] < new Date(new Date().setHours(0, 0, 0, 0))) {
    return callback(new Error('开始日期须 大于等于 今天'))
  }
  return callback()
}
const returnRules = {
  instruction: [{ required: true, trigger: "blur", message: "不能为空" }],
  returnValidityPeriod: [
    { required: true, trigger: "blur", message: "不能为空" },
    { required: true, validator: validatePlanPackingDate, trigger: "blur" }
  ],
  yardName_: [{ required: true, trigger: "change", message: "不能为空" }],
  contacts: [{ required: true, trigger: "change", message: "不能为空" }],
}

const typeList = computed(() => {
  const list = [{ id: 0, name: '全部' }, { id: 5, name: '已发放' }, { id: 10, name: '已下载' }, { id: 15, name: '还箱中' },{ id: 20, name: '已完成' }]
  return list
})
const orderTypeval = ref("")

onMounted(() => {
  nextTick(() => {
    if(isAgent.value){
          orderTypeval.value = "5"
    }else{
           orderTypeval.value = "10"
    }
    getTableData()
    })

})
// //监听 tagName
// import orderInfo from '../../../store/modules/order'
// watch(() => orderInfo().tagName, (val: any) => {
//   console.log(val)
//   param.tagName = val
//   getTableData();
// },{immediate:true})
// 获取路径参数和查询参数
// const paramsAndQuery = computed(() => ({
//   query: route.name
// }));
// watch(
//   paramsAndQuery,
//   (newVal, oldVal) => {
//     if(newVal.query=='JKhuanXiangManageXD4'){
//       param.tagName = 'returnBox'
//     }else{
//       param.tagName = 'rent'
//     }
//   getTableData()
//   },
//   {immediate:true}
// );
function handleTypeChange(val: any) {
  param.status = val
  getTableData()
}

function getTableData() {
  let data = {
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    returnBoxNo: param.returnBoxNo,
    yardName: param.yardName,
    orderType:orderTypeval.value,
    returnBoxType: param.returnBoxType,
    status: param.status,
    orderNo: param.orderNo,
    agentName: param.agentName,
  }
  
  table.config.loading = true;
  // 获取列表数据
  getBoxruntEastTable(formData.value.id).then((res: any) => {
    table.data = res.data;
    // table.data.forEach((item: any) => {
    //   let orderList = JSON.parse(item.orderList)
    //   item.orderNoList = orderList.map((item: any) => item.orderNo).join('/')
    // })
    // table.config.total = res.data.total;
  })
  table.config.loading = false;
}
function handleReSet() {
  param.returnBoxNo = null
  param.yardName = null
  param.returnBoxType = ''
  param.status = null
  param.agentName = null
  param.orderNo = null
  getTableData()
}

//分页
function onTablePageChange(page: any) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

//下载还箱单
const downloadFile = (rowData: any) => {
  if (rowData.pdfFile) {
    let pdfFile = JSON.parse(rowData.pdfFile)
    pdfFile=pdfFile[0]
    if (!pdfFile.url) return ElMessage.error('chengzhi 未找到文件')
    downloadIamge(pdfFile.url,pdfFile.originalFileName || new Date(Date.now()+28800000).toISOString())
  } else {
    // console.log(rowData)
    ElMessage.error('chengzhi 未找到文件')
  }
}

// 添加还箱记录
const rowData = ref({})
const activeAddPacking = (row: any) => {
  rowData.value = row
  let boxType = JSON.parse(rowData.value.containerCountList)[0].boxType
  rowData.value.boxType = boxTypeFilter(boxType)
  // getReturnEastData(row.id).then((res: any) => {
  //   returnInfo.value = res.data
  // })

  param.drawerReturnBox = true
}

//查看还箱记录
const packingRecord = ref([])
const showReturnRecord = (row: any) => {
  param.drawer3 = true
  rowData.value = row
  const data = {
    pageNum: 1,
    pageSize: 200,
    returnBoxId: row.returnBoxId
  }
  getDetailTable(data).then((res: any) => {
    let list = res.data.list
    list.forEach((item: any) => {
      item.boxCondition = boxConditionFilter(item.boxCondition)
      item.boxType = boxTypeFilter(item.boxType)
      item.returnDate = formatDate(item.returnDate, 2)
    })
    packingRecord.value = list

  })
}

//查看还箱单详情
const indexInfoRef=ref()
const showInfo = (row: any) => {
  row.id=row.returnBoxId
  indexInfoRef.value.openBox(row)
};
//关闭弹框
const returnFormRef=ref()
const fileList=ref([]) //附件默认
const close = () => {
  // returnFormRef.value.resetFields()
  param.rentOrderTable=[]
  param.returnValidityPeriod=[]
  param.instruction=null
  param.yardName_=null
  yardInfo.value={}
  selectBoxList.value=[]
  fileList.value=[]
  param.drawer1 = false;
  param.drawer2 = false
  param.drawer3 = false
  packingRef.value.resultList=[]
}
// 去开还箱单(//param.oprType 5-还箱单 10-箱属 15-还箱令  )
const goCreateReturn = (type: number) => {
  param.drawer1 = true
  param.oprType = type
  param.rentBoxTable = []
}
const { proxy } = getCurrentInstance();
const handleSubmit = (drawer: string) => {
  proxy.$refs.returnFormRef.validate(valid => {
    if (!valid) return
    handleAddReturn()
  })
}
//开还箱单 orderList
const tableRef = ref({ multipleSelection: [] });
const packingRef = ref()
const handleAddReturn = async () => {
  let orders = JSON.parse(JSON.stringify(param.rentOrderTable)) //订单list 
  if (!orders[0] || !orders[0].orderNo) {
    ElMessage.warning("订单不能为空！")
    return
  }
  const imgList = await packingRef.value.resultList || []
  if (param.oprType > 5 && imgList.length == 0) {
    ElMessage.warning("附件不能为空！")
    return
  }
  let orderList: any = []
  let containerNoList: any[] = []
  let containerCountList: any[] = []
  orders.forEach((el: any) => {
    // orderList.push({ "orderId": el.orderId, "orderNo": el.orderNo, "returnValidityPeriod": param.returnValidityPeriod }) // 大BUG
    orderList.push({ "orderId": el.orderId, "orderNo": el.orderNo })
    containerCountList.push({ boxType: el.boxType, boxQuantity: el.boxQuantity, boxCondition: el.boxCondition })
  })
  selectBoxList.value.forEach((el: any) => {
    containerNoList.push({ "containerId": el.id, "containerNo": el.containerNo })
  })
  const data = {
    "returnBoxType": param.oprType,
    "boxEastYardId": yardInfo.value.id,
    "orderList": JSON.stringify(orderList), //"[{\"orderId\":1,\"orderNo\":\"2222\"}]", ？
    "containerNoList": JSON.stringify(containerNoList), //"[{\"containerId\":1,\"containerNo\":\"2222\"}]",
    "containerCountList": JSON.stringify(containerCountList), //"[{\"boxType\":5,\"boxCondition\":\"10\",\"boxQuantity\":\"11\"}]" ？
    detailFileList: JSON.stringify(imgList) || null,
    yardContactSerialNo: yardInfo.value.yardContactSerialNo
  }

  if (param.returnValidityPeriod && param.returnValidityPeriod.length == 2) {
    data.returnValidityPeriodStart = param.returnValidityPeriod[0]
    data.returnValidityPeriodEnd = param.returnValidityPeriod[1]
  }

  if (param.oprType == 5) {  // 5-还箱单(回调箱) 10-箱属(租箱) 15-还箱令(租箱)  
    data.instruction = param.instruction //指令号
    data.containerClassify = 10  //集装箱分类(5-租箱 10-回调)
  }
  if (param.oprType == 10) {
    data.boxOwnerContent = param.boxOwnerContent
    // data.detailFileList = null
    data.containerClassify = 5
  }
  if (param.oprType == 15) {
    // data.detailFileList = null
    data.instruction = param.instruction //指令号
    data.containerClassify = 5
  }
  addReturn(data).then((res: any) => {
    param.returnId = res.data.id
    ElMessage.success('还箱单已生成')
    close()
    getTableData()
  })
}

//选择集装箱
const choiceBox = () => {
  param.isExist = true
  getBoxTableData()
  param.drawerSelectBox = true
}
let selectBoxList = ref([])
const handleChoiceBox = () => {
  param.drawerSelectBox = false
  let arry: any = []
  selectBoxList.value.forEach((el: any) => {
    arry.push(el.orderId)
  })
  arry = [...new Set(arry)]

  if (arry.length < 1) {
    ElMessage.warning("请选择箱号！")
    return
  }
  if (param.oprType == 5) { // 5-还箱单(回调箱) 10-箱属 15-还箱令  
    getHuiDiaoOrderList({ "orderIds": arry }).then((res: any) => {
      let list = res.data;
      list.forEach((el: any) => {
        el.returnWaitQuantity = el.boxQuantity - el.returnedQuantity
        el.packedWaitQuantity = el.boxQuantity - el.packedQuantity
        el.createTime = formatDate(el.createTime, 2)
      });
      param.rentOrderTable = list
    })
  } else {
    getRentOrderList({ "orderIds": arry }).then((res: any) => {
      let list = res.data;
      list.forEach((el: any) => {
        el.returnWaitQuantity = el.boxQuantity - el.returnedQuantity
        el.packedWaitQuantity = el.boxQuantity - el.packedQuantity
        el.createTime = formatDate(el.createTime, 2)
      });
      param.rentOrderTable = list
    })
  }
}
const handleSelectionBoxChange = (list: any) => {
  selectBoxList.value = list
}

//堆场组件 emit 
const yardInfo = ref({})
const yardInfoData = (id: string, info: any) => {
  // param.location = id
  if (info) {
    param.yardName_ = info.yardName
    console.log(info,"----","sss")
    yardInfo.value = info
    yardInfo.value.yardContacts = info.yardContacts ? JSON.parse(info.yardContacts) : []
    //获取联系人&&默认第一个
    handleYardContactsChange(yardInfo.value.yardContacts[0])
  }
}

//获取 箱子列表
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
function getBoxTableData() {
  const containerNos = getContainerNos()
  let orderIds: any = []
  let returnCityId=yardInfo.value?.cityId || ''
  if(param.oprType==5 && orderTypeval.value=='10'){
    returnCityId= ''
  }
  let data = {
    statusList: [20], //集装箱 未还
    containerNos: containerNos.length > 1 ? containerNos : [],
    containerNo: containerNos.length == 1 ? containerNos[0] : null,
    orderIds: orderIds,
    orderType:orderTypeval.value,
    returnCityId:returnCityId,
    // boxEastYardId: yardInfo.value.id,
    boxEastOperatorUserId: userStore.getUser().id,
    pageNum: 1,
    pageSize: 200,
  };

  // if(data.containerNos.length > 0){
  //   data.boxEastYardId = null
  // }
  // if(param.isExist){
  //   data.boxEastYardId = null
  // }
  // if(param.tagName == "returnBox"){
  //     data.orderType ="10"
  // }else{
  //   data.orderType ="5"
  //   // data.containerClassify = (param.oprType == 5 ? 10 : 5)// (param.oprType 5-还箱单(回调箱) 10-箱属 15-还箱令)  (containerClassify 5-租箱 10-回调)
  // }
  getBoxTable(data).then(res => {
    let list = res.data.list;
    param.isExist = false
    list.forEach((el: any) => {
      el.boxType = boxTypeFilter(el.boxType)
      el.boxCondition = boxConditionFilter(el.boxCondition)
    });
    param.selectBoxTable = list;
  });
}

// 获取箱号
const getContainerNos = () => {
  let containerNos = [] //param.containerNos ? param.containerNos.split(",") :
  if (param.containerNos) {
    const dos = param.containerNos.indexOf(",") > -1 ? ',' : '，'
    containerNos = param.containerNos.split(dos).map((item) => item.trim())
  }
  return containerNos
}

//箱型量
const getFormatNum = (arry: any) => {
  console.log(arry)
  let str = ''
  let typeList: any = []
  if (arry.length == 0 || !arry[0].orderNo) return 0 // 过滤初始值影响 { orderNo: '', planPickupDate: '', createTime: '' }
  arry.forEach((el) => {
    if (!typeList.includes(el.boxType)) {
      typeList.push(el.boxType)
    }
  })
  typeList.forEach((el) => {
    let num = 0
    arry.forEach((el2) => {
      if (el2.boxType == el) {
        num += (el2.boxQuantity - 0)
      }
    })
    let dos = str == '' ? '' : '、'
    str = dos + boxTypeFilter(el) + '*' + num
  })
  if (str) {
    return str
  } else {
    return 0
  }
}

//联系人切换
const handleYardContactsChange = (val: any) => {
  if (!val) return
  yardInfo.value.contacts = val.contacts
  param.contacts = val.contacts // to pass jiaoyan
  yardInfo.value.tel = val.tel
  yardInfo.value.areaCode = val.areaCode
  yardInfo.value.email = val.email
  yardInfo.value.yardContactSerialNo = val.yardContactSerialNo
}

//过滤
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 15, label: '适货' }, { value: 10, label: '次新' }, { value: 20, label: '混提' },{ value: 5, label: '全新' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
//  //5-还箱单 10-箱属  15-还箱令
const returnTypeFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 5, label: '还箱单' }, { value: 10, label: '箱属' }, { value: 15, label: '还箱令' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
</script>

<style scoped>
.el-form-diy {
  padding: 10px;

  div {
    width: 100%;
  }
}
</style>
